/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slsBeans;

import EL.*;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;

/**
 *
 * @author Tian
 */
@Stateless
public class RestaurantBLO implements RestaurantBLORemote
{

    @PersistenceContext(unitName = "Tunga_EJB3PU")
    private EntityManager em;

    public List<Restaurants> getAll()
    {
        String hql = "FROM Restaurants";
        Query query = this.em.createQuery(hql);
        List<Restaurants> restaurants = query.getResultList();
        return restaurants;
    }

    public Contacts getByID(int id)
    {
        Contacts contact = em.find(Contacts.class, id);
        return contact;
    }

    public Restaurants getByName(String name)
    {
        String hql = "FROM Restaurants as r WHERE r.name = ?1";
        Query query = this.em.createQuery(hql);
        query.setParameter(1, name);
        Restaurants res = (Restaurants) query.getSingleResult();
        return res;
    }

    public boolean add(Restaurants restaurant, Contacts contact)
    {

        try
        {
            contact.setRestaurants(restaurant);
            restaurant.setContacts(contact);
            this.em.persist(contact);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public boolean edit(Contacts contact)
    {
        try
        {
            this.em.merge(contact);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    public boolean delete(int id)
    {
        Contacts contact = getByID(id);
        if (contact != null)
        {
            try
            {
                this.em.remove(contact);
                return true;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    public Restaurants getResByID(int id)
    {
        Restaurants res = this.em.find(Restaurants.class, id);
        return res;
    }

}
